var fs = require('fs');
var path = require('path');
var colors = require('colors');
var jsonpack = require('jsonpack');
try {
    var prjid = process.argv[2].split('=')[1];
    if (!prjid) {
        console.error('PrjId not defined!\nUse prjid=xxx to specify a prjid!'.red);
        return;
    }
} catch (err) {
    console.error('PrjId not defined!\nUse prjid=xxx to specify a prjid!'.red);
    return;
}



var config = require('./config.json');
config.sort(function(a, b) {
    return a.order > b.order ? 1 : -1;
});
console.log(config);
var datas = [];
var readFile = function(index) {
    index = index || 0;
    var file = config[index].file,
        name = config[index].name;
    var fileName = './datas/' + file;
    fs.readFile(fileName, (function(index, name) {
        return function(err, data) {
            if (err) throw err;
            var item = {
                data: JSON.parse(data.toString()),
                name: name
            };
            datas.push(item);
            index++;
            if (index < config.length) {
                readFile(index);
            } else {
                onReadComplete();
            }

        };
    })(index, name));
};
var onReadComplete = function() {
    var jsonConverters = require('./jsonConverters');
    var topojson = require('topojson');
    var converter = jsonConverters.esriConverter();
    datas.forEach(function(item) {
        var geojson = converter.toGeoJson(item.data);
        item.data = jsonpack.pack(geojson);
        //item.data = geojson;
    });
    fs.writeFile('./datas.txt', JSON.stringify(datas));
    upload(datas);
};

var upload = function(list) {
    var request = require('request');
    var urlApi = 'http://61.129.33.248:8084/MetroDataApi/api/getprojectlayers/' + prjid;
    request({
        method: 'PUT',
        url: urlApi,
        json: JSON.stringify(list)
    }, function(error, response, body) {
        console.log(body);
    });
};


readFile();
